package cn.weiyan.dtx.txmsgdemo.bank2.server.impl;

import cn.weiyan.dtx.txmsgdemo.bank2.dao.AccountInfoDao;
import cn.weiyan.dtx.txmsgdemo.bank2.model.AccountChangeEvent;
import cn.weiyan.dtx.txmsgdemo.bank2.server.AccountInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author misterWei
 * @create 2020年02月16号:12点55分
 * @mailbox mynameisweiyan@gmail.com
 */
@Service
@Slf4j
public class AccountInfoServiceImpl implements AccountInfoService{

    @Autowired
    private AccountInfoDao accountInfoDao;

    private int reload = 0 ;

    /**
     * 该方法为消费方,只要该生产方的消息传达到这里,消息就必须执行,如果报错,就会一直重试.
     * @param accountChangeEvent
     */
    @Override
    @Transactional
    public void addAccountInfoBalance(AccountChangeEvent accountChangeEvent) {
     //幂等性判断
        int existTx = accountInfoDao.isExistTx(accountChangeEvent.getTxNo());
        if (existTx > 0){
            return;
        }
        accountInfoDao.updateAccountBalance(accountChangeEvent.getAccountNo(),accountChangeEvent.getAmount());

        accountInfoDao.addTx(accountChangeEvent.getTxNo());

        log.error("当前消息重试次数为 : "+ reload);

        reload ++;

        if (accountChangeEvent.getAmount() == 4) {
            throw new RuntimeException("bank2 制造异常...");
        }
    }
}
